/**
 * Description:
 * Class Name:ExecuteDML
 * Date:2022/4/4 16:56
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_4_执行SQL语句的方式._13_4_1_使用executeUpdate方法来执行DDL和DML语句;

import java.io.FileInputStream;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

public class ExecuteDML {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFile) throws Exception{
        var props = new Properties();
        props.load(new FileInputStream(paramFile));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public int insertData(String sql) throws Exception{
        // 加载驱动
        Class.forName(driver);
        try (
                // 获取数据连接
                var connection = DriverManager.getConnection(url, user, pwd);
                // 获取Statement对象
                Statement statement = connection.createStatement();
                ){
            return statement.executeUpdate(sql);
        }
    }

    public static void main(String[] args) throws Exception {
        var ed = new ExecuteDML();
        ed.initParam("./Chapter_13_mysql.ini");

        String temp_sql = "insert into jdbc_test" +
                "(jdbc_name, jdbc_desc)" +
                " select s.student_name, t.teacher_name" +
                " from student_table s, teacher_table t" +
                " where s.java_teacher = t.teacher_id;";

        int result = ed.insertData(temp_sql);
        System.out.println("---一共有 " + result + "条记录受到影响");
        System.out.println(System.getProperty("user.dir"));
    }
}
